package com.xwtech.cring.admin.pub;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.filter.OncePerRequestFilter;

import com.xwtech.cring.admin.pub.AdminLoginToken;
import com.xwtech.framework.login.pub.AbstractLoginToken;
import com.xwtech.framework.pub.result.ResultConstants;
import com.xwtech.framework.pub.result.ResultInfo;
import com.xwtech.framework.pub.result.ResultInfos;
import com.xwtech.framework.pub.utils.SessionUtils;
import com.xwtech.framework.pub.web.RequestNameConstants;
import com.xwtech.framework.pub.web.SessionNameConstants;

/**
 * 后台权限URL过滤 防止无权限的登录用户通过.jsp或.do的URL直接访问非授权的功能
 * 只过滤/cring/jsp/admin/user/*.do和/cring/jsp/admin/user/*.jsp下的链接
 * 
 * @author fengqi
 * 
 */
public class AdminUserUrlFilter extends OncePerRequestFilter {

	private static final Log log = LogFactory.getLog(AdminUserUrlFilter.class);

	private static final List noFilterList = new ArrayList();

	static {
		noFilterList.add("login.jsp");
		noFilterList.add("login.do");
		noFilterList.add("main.jsp");
		noFilterList.add("logout.jsp");
		noFilterList.add("header.jsp");
		noFilterList.add("menu.jsp");
		noFilterList.add("footer.jsp");
		noFilterList.add("bgUsermodifyPwd.jsp");   // 修改密码之页面和方法url
		noFilterList.add("bgUserModifyPwd.do");
	}

	protected void doFilterInternal(HttpServletRequest request,
			HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {

		String currentUrl = request.getRequestURI();
		String queryUrl = request.getRequestURI();
		if (request.getQueryString() != null
				&& (!request.getQueryString().equals(""))) {
			// 获得带参数的url（相对路径）
			queryUrl = currentUrl + "?" + request.getQueryString();
		}
		
		String compareUrl = currentUrl.substring(
				currentUrl.lastIndexOf("/") + 1, currentUrl.length());
		if (AdminUserUrlFilter.noFilterList.contains(compareUrl)) {
			// 该页面不在需要过滤的范围之内
			log.debug("路径" + currentUrl + "不需要过滤...");
			filterChain.doFilter(request, response);
			return;
		}
		
		AbstractLoginToken loginToken = (AdminLoginToken) SessionUtils
				.getObjectAttribute(request, SessionNameConstants.LOGIN_TOKEN);
		String currentUser = loginToken.getFrameLogin().getLoginName();

		log.debug("用户" + currentUser + "正在尝试相对路径为" + queryUrl + "的链接......");
		
		// 判断用户是否是超级管理员：如果是，则不需要验证，直接跳转
		if (currentUser.equalsIgnoreCase(AdminUserBizConst.SUPER_ADMIN_LOGIN_NAME)) { 
			log.debug("该用户为超级管理员，不需要校验...");
			filterChain.doFilter(request, response);
			return;
		}

		// 用loginToken(AdminLoginToken)中获得该用户所拥有访问权限的url（包括jsp和.do）
		Set urlSet = loginToken.getUrlSet();
		if (urlSet.contains(currentUrl) || urlSet.contains(queryUrl)) {
			log.debug("该URL在此用户的权限范围之内，允许进入...");
			filterChain.doFilter(request, response);
		} else {
			log.debug("该用户是无权用户，跳转到提示页面...");
			HashMap map = new HashMap();
			ResultInfos resultInfos = new ResultInfos();
			resultInfos.add(new ResultInfo(ResultConstants.NOT_ACCESS_ROLE,
					null));
			map.put(RequestNameConstants.RESULTINFOS, resultInfos);
			request.setAttribute(RequestNameConstants.INFORMATION, map);
			request.getRequestDispatcher("/cring/jsp/admin/information.jsp")
					.forward(request, response);
			return;
		}
	}

}
